package com.atdfrz.secondshop.controller.user;

import com.atdfrz.secondshop.dto.LayuiResult;
import com.atdfrz.secondshop.mapper.CategoryMapper;
import com.atdfrz.secondshop.mapper.ProductMapper;
import com.atdfrz.secondshop.pojo.Cart;
import com.atdfrz.secondshop.pojo.Category;
import com.atdfrz.secondshop.pojo.Product;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.UUID;

@RestController
public class FileController extends BaseController implements WebMvcConfigurer  {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd/");
    Date now1=new Date();
    @PostMapping("/upload")
    @ResponseBody
    public LayuiResult upload(MultipartFile file, HttpServletRequest req,
                         @RequestParam("category") String category, @RequestParam("name") String name,
                         @RequestParam("price") Integer price, @RequestParam("description") String description,
                         @RequestParam("amount") Integer amount, Model model,HttpSession session) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        LayuiResult<Object> result = new LayuiResult<>();
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        //查询名字为 Tom 的一条记录
        queryWrapper.eq("name",category);
        Category category1 = categoryMapper.selectOne(queryWrapper);
        String format=sdf.format(new Date());
        File folder=new File("c:/cx/test/pic/");
        if(!folder.isDirectory()){
            if(!folder.mkdirs()){
//                return "文件夹创建失败";
                result.setCode(3);
                result.setMessage("文件夹创建失败");
                return result;
            }
        }
        System.out.println(folder.getPath());
        String oldName=file.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        Product product=new Product();
        product.setCategoryId(category1.getCategoryId());
        product.setName(name);
        product.setPhoto(newName);
        product.setPrice(price);
        product.setDescription(description);
        product.setAmount(amount);
        product.setCreateTime(now1);
        product.setSales(0);
        product.setUserId(userid);
        try {
            file.transferTo(new File(folder,newName));
//            String filePath=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/files/test/pic/"+newName;
//            return filePath;
            productMapper.insert(product);
//            return "添加成功！";
            result.setCode(1);
            result.setMessage("添加成功");
            return result;
        }catch (IOException e){
            e.printStackTrace();
        }
//        return "添加失败！";
        result.setCode(2);
        result.setMessage("修改失败");
        return result;
    }
    //修改商品信息
    @PostMapping("/update")
    @ResponseBody
    public LayuiResult update(MultipartFile file, HttpServletRequest req,
                         @RequestParam("category1") String category, @RequestParam("name1") String name,
                         @RequestParam("price1") Integer price, @RequestParam("description1") String description,
                         @RequestParam("amount1") Integer amount,@RequestParam("productId") Integer productId, Model model) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        LayuiResult<Object> result = new LayuiResult<>();
        //查询分类ID对应的分类名
        queryWrapper.eq("name",category);
        Category category1 = categoryMapper.selectOne(queryWrapper);
        String format=sdf.format(new Date());
        File folder=new File("c:/cx/test/pic/");
        if(!folder.isDirectory()){
            if(!folder.mkdirs()){
                result.setCode(3);
                result.setMessage("文件夹创建失败");
                return result;
            }
        }
        System.out.println(folder.getPath());
        String oldName=file.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        Product product=new Product();
        product.setCategoryId(category1.getCategoryId());
        product.setName(name);
        product.setProductId(productId);
        product.setPhoto(newName);
        product.setPrice(price);
        product.setDescription(description);
        product.setAmount(amount);
        product.setCreateTime(now1);
        product.setSales(0);
        try {
            file.transferTo(new File(folder,newName));
//            String filePath=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/files/test/pic/"+newName;
//            return filePath;
//            productMapper.insert(product);
            productMapper.updateById(product);
            result.setCode(1);
            result.setMessage("修改成功");
            return result;
        }catch (IOException e){
            e.printStackTrace();
        }
        productMapper.updateById(product);
        result.setCode(2);
        result.setMessage("修改失败");
        return result;
    }



    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**").addResourceLocations("file:c:/cx/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

    //删除购物车中的商品
    @PostMapping("/release/deleteProduct")
    @ResponseBody//添加商品到购物车
    public LayuiResult deleteNum(@RequestBody Product product) {
        LayuiResult<Object> result = new LayuiResult<>();
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (product != null) {
            wrapper.eq(Product::getProductId, product);
            productMapper.deleteById(product.getProductId());
            result.setCode(1);
            result.setMessage("删除成功");
            return result;
        }
        result.setCode(2);
        result.setMessage("删除失败");
        return result;
    }

//
//        Integer productId = cart.getProductId();
//        wrapper.eq(productId != null, Cart::getProductId, productId);
//        int delete = cartMapper.delete(wrapper);
//        if (delete != 0) {
//            result.setCode(1);
//            return result;
//        } else {
//            result.setCode(0);
//            return result;
//        }
//

}
